package com.mky.mkcompany.dao;

import com.mky.mkcompany.model.UserDoTest;
import com.mky.mkcompany.model.UserDoTestQuest;
import com.mky.mkcompany.model.view.UserFalseQuest;
import com.mky.mkcompany.model.view.UserFalseQuestCount;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Transactional
public interface UserDoTestQuestDao extends JpaRepository<UserDoTestQuest, String> {
    @Query("select new com.mky.mkcompany.model.view.UserFalseQuest(q.id,sc.name,c.name,q.testCentre) from UserDoTestQuest uq,TestQuest q," +
            "SubjectChapter c,SubjectCategory sc where uq.userId=:userId" +
            " and uq.handPaperId=:handPaperId and uq.answerResult=2 and uq.type=2 and uq.questId=q.id " +
            "and q.chapterId=c.id and c.subjectId=sc.id")
    List<UserFalseQuest> findFalseQuest(@Param("userId") String userId,
                                        @Param("handPaperId") String handPaperId);

    List<UserDoTestQuest> findByUserIdAndTestIdAndType(String userId,String testId,Integer type);

    List<UserDoTestQuest> findByUserIdAndHandPaperIdAndType(String userId,String handPaperId,Integer type);

    @Query("select new com.mky.mkcompany.model.view.UserFalseQuestCount(uq.questId,uq.updateTime,count(uq.questId)) from UserDoTestQuest uq,TestQuest q" +
            " where uq.userId=:userId and uq.answerResult=2 and uq.type=2 " +
            "and uq.questId=q.id and q.examType=:examType group by uq.questId")
    List<UserFalseQuestCount> findFalseQuestByUserId(@Param("userId") String userId,@Param("examType") String examType);

    @Query("select uq.id from UserDoTestQuest uq where uq.questId=:questId and uq.answerResult=2 and uq.type=2 group by userId")
    List<String> findCountByQuestId(@Param("questId") String questId);

    List<UserDoTestQuest> findByUserIdAndQuestIdAndAndAnswerResultAndType(String userId,String questId,Integer answerResult,Integer type );


    @Transactional
    @Modifying
    @Query("delete from UserDoTestQuest where questId = ?1 ")
    void deleteByQuestId(String questId);

    @Transactional
    @Modifying
    @Query("delete from UserDoTestQuest where testId = ?1 ")
    void deleteByTestId(String testId);


    @Transactional
    @Modifying
    @Query("delete from UserDoTestQuest where questId in (:questIds) ")
    void deleteByQuestIds(@Param("questIds")List<String> questIds);

    @Transactional
    @Modifying
    @Query("delete from UserDoTestQuest where userId = ?1 ")
    void deleteByUserId(String userId);
}